using System;
using System.Globalization;
using System.Windows.Data;
using OFX.Aggregator.WpfApplication.Properties;

namespace OFX.Aggregator.WpfApplication
{
	[ValueConversion(typeof (DateTime), typeof (string))]
	public class TimeSpanConverter : IValueConverter
	{
		#region IValueConverter Members

		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var dateTime = (DateTime?) value;

			if (!dateTime.HasValue)
				return Resources.TimeSpan_None;

			TimeSpan timeSpan = DateTime.Now - dateTime.Value;

			// span is less than or equal to 60 seconds, measure in seconds.
			if (timeSpan <= TimeSpan.FromSeconds(60))
			{
				return string.Format(Resources.TimeSpan_Format_SecondsAgo, timeSpan.Seconds);
			}

			// span is less than or equal to 60 minutes, measure in minutes.
			if (timeSpan <= TimeSpan.FromMinutes(60))
			{
				return timeSpan.Minutes > 1
				       	? string.Format(Resources.TimeSpan_Format_MinutesAgo, timeSpan.Minutes)
				       	: Resources.TimeSpan_MinuteAgo;
			}

			// span is less than or equal to 24 hours, measure in hours.
			if (timeSpan <= TimeSpan.FromHours(24))
			{
				return timeSpan.Hours > 1
				       	? string.Format(Resources.TimeSpan_Format_HoursAgo, timeSpan.Hours)
				       	: Resources.TimeSpan_HourAgo;
			}

			// span is less than or equal to 30 days (1 month), measure in days.
			if (timeSpan <= TimeSpan.FromDays(30))
			{
				return timeSpan.Days > 1
				       	? string.Format(Resources.TimeSpan_Format_DaysAgo, timeSpan.Days)
				       	: Resources.TimeSpan_DayAgo;
			}

			// span is less than or equal to 365 days (1 year), measure in months.
			if (timeSpan <= TimeSpan.FromDays(365))
			{
				return timeSpan.Days > 30
				       	? string.Format(Resources.TimeSpan_Format_MonthsAgo, timeSpan.Days/30)
				       	: Resources.TimeSpan_MonthAgo;
			}

			// span is greater than 365 days (1 year), measure in years.
			return timeSpan.Days > 365
			       	? string.Format(Resources.TimeSpan_Format_YearsAgo, timeSpan.Days/365)
			       	: Resources.TimeSpan_YearAgo;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotSupportedException();
		}

		#endregion
	}
}